﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;
namespace RL.Scheduling
{
    public class TimerExtended
    {
        Timer timer = null;
        public event TimerEvent Tick = null;
        public string FriendlyApplicationNameForLogging = string.Empty;
        EventLogX logger = new EventLogX();
        public TimerExtended()
        {
            timer = new Timer();
            logger.AddRLInfoEntry(1, FriendlyApplicationNameForLogging, "timer constructor called");
        }
        private double _interval = 0;
        public void Start(double interval)
        {
            logger.AddRLInfoEntry(2, FriendlyApplicationNameForLogging, "timer started called");
            _interval = interval;
            timer = new System.Timers.Timer(_interval);
            // Set to run more than once
            timer.AutoReset = true;
            // Delegate to handle the timer event
            timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
            // Start the timer
            timer.Start();
            // Prevents garbage collection from occuring in long running methods
            GC.KeepAlive(timer);
        }
        public void Start() { Start(10000); }
        public void Start(TimerSeconds seconds) 
        {
            Start(double.Parse(seconds.GetStringValue()) * 1000);
        }
        public void Stop()
        {
            this.timer.Stop();
            this.Tick = null;            
            this.timer.Dispose();
        }
        void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            logger.AddRLInfoEntry(3,FriendlyApplicationNameForLogging, "timer elapsed called.");
            if (null == Tick)
            {
                throw new Exception("Set timer's Tick event.");
            }
            timer.Stop();
            this.Tick();
            this.Start(_interval);
        }
    }
    public delegate void TimerEvent();
    public enum TimerSeconds
    {
        [StringValue("3")]
        a_Three = 3,
        [StringValue("5")]
        b_Five = 5,
        [StringValue("7")]
        c_Seven = 7,
        [StringValue("10")]
        d_Ten = 10,
        [StringValue("15")]
        e_Fiften = 15,
        [StringValue("25")]
        f_TwentyFive = 25,
        [StringValue("60")]
        g_Sixty = 60,
        [StringValue("90")]
        h_Ninty = 90,
        [StringValue("120")]
        i_OneTwenty=120,
        [StringValue("240")]
        j_TwoForty=240,
        [StringValue("360")]
        k_ThreeSixty=360
    }
}
